package com.dmxh.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dmxh.mapper.TbSellerMapper;
import com.dmxh.pojo.TbSeller;
import com.dmxh.pojo.TbSellerExample;
import com.dmxh.result.Result;
import com.dmxh.result.ResultConstant;
import com.dmxh.service.SellerService;
import com.dmxh.util.ShiroUtils;
import com.dmxh.vo.PasswordVo;
import com.dmxh.vo.SellerVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class SellerServiceImpl implements SellerService {

    @Autowired
    private TbSellerMapper tbSellerMapper;

    @Override
    public TbSeller queryByName(String name) {
        TbSellerExample tbSellerExample = new TbSellerExample();
        tbSellerExample.createCriteria().andSellerIdEqualTo(name);
        List<TbSeller> tbSellers = tbSellerMapper.selectByExample(tbSellerExample);
        if (tbSellers.size() > 0) {
            return tbSellers.get(0);
        }
        return null;
    }

    @Override
    public void updateInfo(SellerVo sellerVo) {
        TbSeller tbSeller = new TbSeller();
        BeanUtils.copyProperties(sellerVo, tbSeller);
        tbSellerMapper.updateByPrimaryKeySelective(tbSeller);
    }


    @Override
    public void register(TbSeller tbSeller) {
        String salt = ShiroUtils.generateSalt(32);
        String password = ShiroUtils.encryptPassword("md5", tbSeller.getPassword(), salt, 7);
        tbSeller.setPassword(password);
        tbSeller.setSalt(salt);
        tbSellerMapper.insertSelective(tbSeller);
    }

    @Override
    public Result updatePassword(String username, String pass, String oldpass) {
        TbSeller tbSeller = queryByName(username);
        String password = ShiroUtils.encryptPassword("md5", oldpass, tbSeller.getSalt(), 7);
        if (StrUtil.equals(password, tbSeller.getPassword())) {
            String salt = ShiroUtils.generateSalt(32);
            String passwordfinal = ShiroUtils.encryptPassword("md5", pass, salt, 7);
            tbSeller.setPassword(passwordfinal);
            tbSeller.setSalt(salt);
            tbSellerMapper.updateByPrimaryKeySelective(tbSeller);
            return Result.ok();
        }
        return Result.response(ResultConstant.ERROR_CHANGEPASSWORD);
    }

}
